package com.ibl.rover.lite.client.Utility;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import android.os.Environment;
import android.widget.Toast;

import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.common.bean.OrderBean;
import com.ibl.rover.lite.common.bean.ProductOrderBean;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.DatabaseManager;
import com.ibl.rover.lite.common.db.Criteria.Operators;

public class OrderExport {

	private ApplicationContext roverApp = null;
	private DatabaseManager manager;
	private String productCode;
	private String productQuantity;
	private String productUnitPrice;
	private Logger logger = new Logger();

	public OrderExport(ApplicationContext context) {
		roverApp = context;
		manager = roverApp.getDatabaseManager();
	}

	public void generateCsvFile(String sFileName) {
		FileWriter writer = null;
		try {
			File dir = Environment.getExternalStorageDirectory();
			File logFileCreation = new File(dir, roverApp.getUserName()+new Date().getDate()+new Date().getHours()+new Date().getMinutes()+".txt");

			writer = new FileWriter(logFileCreation);
			
			writer.write(buildOrderResponse(new StringBuilder()));

		} catch (Exception e) {
			logger.logException("Exception in Generating File  ", e);
		} finally {

			try {
				writer.flush();
				writer.close();
				roverApp.showMessage("File Sucessfully Export", Toast.LENGTH_LONG);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.logException("Exception in Clsoing FIle ", e);
			}

		}
	}

	private String buildOrderResponse(StringBuilder builder) {
		try {

			List<OrderBean> orderList = manager.findAllBean(OrderBean.class);
			if (orderList.size() > 0) {
				List<ProductOrderBean> list;
				
				for (OrderBean orderBean : orderList) {
					list = null;
					Criteria<ProductOrderBean> criteria = manager
							.generateCriteria(ProductOrderBean.class);
					criteria.addRestriction("ORDERKEY", Operators.isEqual,
							orderBean.getOrderId());
					list = criteria.execute();
					getCommaSeparatedProductCode(list);

					builder.append(roverApp.getUserName() + ",");
					builder.append(orderBean.getOrderId() + ",");

					builder.append(orderBean.getCustomerCode() + ",");

					builder.append(orderBean.getStatus() + ",");

					builder.append(orderBean.getAmount() + ",");

					builder.append(orderBean.getSalesType() + ",");

					builder.append(productCode + ",");

					builder.append(productQuantity + ",");

					builder.append(productUnitPrice+ "\n");

				}

			}
		} catch (Exception e) {
			logger.logException("Exporitng Order Data Builder ", e);
		}
		return builder.toString();
	}

	private void getCommaSeparatedProductCode(
			List<ProductOrderBean> productOrderList) {
		productCode = "";
		productQuantity = "";
		productUnitPrice = "";
		StringBuilder idsList = new StringBuilder();
		StringBuilder quantityList = new StringBuilder();
		StringBuilder priceList = new StringBuilder();
		for (ProductOrderBean productOrderBean : productOrderList) {
			idsList.append(String.valueOf(productOrderBean.getProductCode())
					+ "#");
			quantityList.append(String.valueOf(productOrderBean.getQuantity())
					+ "#");
			priceList.append(String.valueOf(productOrderBean.getUnitPrice())
					+ "#");
		}
		if (0 < idsList.length()) {
			idsList.deleteCharAt(idsList.length() - 1);
			quantityList.deleteCharAt(quantityList.length() - 1);
			priceList.deleteCharAt(priceList.length() - 1);
		}
		productCode = idsList.toString();
		productQuantity = quantityList.toString();
		productUnitPrice = priceList.toString();
	}

}
